package com.cn.xiaonuo.sys.modular.file.util;


import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;


//https://search.maven.org/artifact/com.qiniu/qiniu-java-sdk/7.0.3/jar
public class QiniuUtil {
      
    /**基本配置-从七牛管理后台拿到*/  
  //设置好账号的ACCESS_KEY和SECRET_KEY  
  static String ACCESS_KEY = "gO_Npd91n9qfOvDmWI7B8TBvnvhoTj45shrdSCNu";
  static String SECRET_KEY = "dkFwLalS7ltq-PFnGTWNegcByaSK_9lMxCDS9VOc";
  //要上传的空间名--  
  static String bucketName = "zyfirst";
    
    
    
  /**指定保存到七牛的文件名--同名上传会报错  {"error":"file exists"}*/  
  /** {"hash":"FrQF5eX_kNsNKwgGNeJ4TbBA0Xzr","key":"aa1.jpg"} 正常返回 key为七牛空间地址 http:/xxxx.com/aa1.jpg
   * @param url
   * @return
   * @throws QiniuException*/
  //上传文件的路径  
//  String FilePath ="D:\\1.png";  
////上传到七牛后保存的文件名    访问为：http://oswj11a86.bkt.clouddn.com/daimo6.png
//  String key = "daimo6.png";    
//  
//  //密钥配置  
//  Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);  
//  //创建上传对象  
//  UploadManager uploadManager =new UploadManager(new Configuration()); 
//    
//  
//  //简单上传，使用默认策略，只需要设置上传的空间名就可以了  
//  public String getUpToken(){  
//      return auth.uploadToken(bucketname);  
//  }  
//

    /**
     * 上传网络图片到七牛云
     * @param url
     * @return
     * @throws QiniuException
     */
    public static  String uploadUrl(String url) throws QiniuException {
        System.out.println(url);
        String s = imageChangeBase64(url);
        System.out.println(s);
        Configuration cfg = new Configuration(Zone.zone2());
        UploadManager uploadManager =new UploadManager(cfg);
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String token = auth.uploadToken(bucketName);
        Response put = uploadManager.put(s.getBytes(), System.currentTimeMillis() + ".jpg", token);

        System.out.println(put);
        return put.bodyString();
    }

    /**
     * 七牛云上传文件  已弃用
     * @param file
     * @return
     */

  public static String uploadFile(File file){
    try {
        //————http上传,指定zone的具体区域——
        //Zone.zone0:华东
        //Zone.zone1:华北
        //Zone.zone2:华南
        //Zone.zoneNa0:北美
        //———http上传，自动识别上传区域——
        //Zone.httpAutoZone
        //———https上传，自动识别上传区域——
        //Zone.httpsAutoZone
        Configuration cfg = new Configuration(Zone.zone2());
    	UploadManager uploadManager =new UploadManager(cfg);
    	Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
       String token = auth.uploadToken(bucketName);

        //调用put方法上传  
      Response res = uploadManager.put(file, file.getName(), token);
      //打印返回的信息  
      System.out.println(res.bodyString());  
      System.out.println(res.statusCode);//200为上传成功
      return res.bodyString();
      } catch (QiniuException e) {  
          Response r = e.response;  
          // 请求失败时打印的异常的信息  
          System.out.println(r.toString());  
          try {
              //响应的文本信息  
            System.out.println(r.bodyString());  
          } catch (QiniuException e1) {  
              //ignore  
          }
          return null;
      }         
  }


    /**
     *     将网络地址对应的图片转换为base64
     * @param imagePath 网络图片路径
     * @return res 图片对应的Base64编码
     */
    public static String imageChangeBase64(String imagePath){
        ByteArrayOutputStream outPut = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        try {
            // 创建URL
            URL url = new URL(imagePath);
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(10 * 1000);

            if(conn.getResponseCode() != 200) {
                return null;//连接失败/链接失效/图片不存在
            }
            InputStream inStream = conn.getInputStream();
            int len = -1;
            while ((len = inStream.read(data)) != -1) {
                outPut.write(data, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        byte[] encode = Base64.getEncoder().encode(outPut.toByteArray());
        String s = new String(encode);
        return "data:image/jpeg;base64,"+s;
    }

  
  public static void main(String args[]) throws IOException{
//    new QiniuUtil().uploadFile(new File("C:\\Users\\zhangyu\\Downloads\\00001.mp4"));
      String s = uploadUrl("http://www.nncc626.com/titlepic/112738/1127380679_1619487241463_title0h.jpg");
      System.out.println(s);
  }  
  
}  
